const Router = require('koa-router')
const { LoginValidator } = require('@validator')
const { User } = require('@models/user')
const { generateToken } = require('@root/core/util')
const { Auth } = require('@root/middlewares/auth')

const router = new Router({
  prefix: '/v1/token'
})

router.post('/', async (ctx) => {
  const obj = await new LoginValidator().validate(ctx)
  const user = await User.verfiyUserNamePassword(obj.get('body.username'), obj.get('body.password'))
  const token = generateToken(user.id, Auth.USER)
  ctx.body = {
    token
  }
})

module.exports = router
